package com.iqiyi.pps.epg.core.utils;

import com.iqiyi.pps.epg.core.model.auth.SysUser;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.*;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 * User: lishunlong
 * Date: 11-2-7
 * Time: 上午11:23
 * 用于处理HTTP请求的工具类
 */
public class RequestUtils {

    /**
     * 获取客户端IP地址，支持proxy
     * @param req HttpServletRequest
     * @return IP地址
     */
    public static String getRemoteAddr(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");
        if(StringUtils.isNotBlank(ip)){
            String[] ips = StringUtils.split(ip,',');
            if(ips!=null){
                for(String tmpip : ips){
                    if(StringUtils.isBlank(tmpip))
                        continue;
                    tmpip = tmpip.trim();
                    if(isIPAddr(tmpip) && !tmpip.startsWith("10.") && !tmpip.startsWith("192.168.") && !"127.0.0.1".equals(tmpip)){
                        return tmpip.trim();
                    }
                }
            }
        }
        ip = req.getHeader("x-real-ip");
        if(isIPAddr(ip))
            return ip;
        ip = req.getRemoteAddr();
        if(ip.indexOf('.')==-1)
            ip = "127.0.0.1";
        return ip;
    }

    public static String getRemotePrivateAddr(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");
        if(StringUtils.isNotBlank(ip)){
            String[] ips = StringUtils.split(ip,',');
            if(ips!=null){
                for(String tmpip : ips){
                    if(StringUtils.isBlank(tmpip))
                        continue;
                    tmpip = tmpip.trim();
                    if(isIPAddr(tmpip)){
                        return tmpip.trim();
                    }
                }
            }
        }
        ip = req.getHeader("x-real-ip");
        if(isIPAddr(ip))
            return ip;
        ip = req.getRemoteAddr();
        if(ip.indexOf('.')==-1)
            ip = "127.0.0.1";
        return ip;
    }

    /**
     * 判断是否为搜索引擎
     * @param req HttpServletRequest
     * @return ture:robot, false,is not robot
     */
    public static boolean isRobot(HttpServletRequest req){
        String ua = req.getHeader("user-agent");
        if(StringUtils.isBlank(ua)) return false;
        return (ua != null
                && (ua.indexOf("Baiduspider") != -1 || ua.indexOf("Googlebot") != -1
                        || ua.indexOf("sogou") != -1
                        || ua.indexOf("sina") != -1
                        || ua.indexOf("iaskspider") != -1
                        || ua.indexOf("ia_archiver") != -1
                        || ua.indexOf("Sosospider") != -1
                        || ua.indexOf("YoudaoBot") != -1
                        || ua.indexOf("yahoo") != -1
                        || ua.indexOf("yodao") != -1
                        || ua.indexOf("MSNBot") != -1
                        || ua.indexOf("spider") != -1
                        || ua.indexOf("Twiceler") != -1
                        || ua.indexOf("Sosoimagespider") != -1
                        || ua.indexOf("naver.com/robots") != -1
                        || ua.indexOf("Nutch") != -1
                        || ua.indexOf("spider") != -1));
    }

    /**
     * 获取COOKIE
     * @param request HttpServletRequest
     * @param name Cookie的名称
     * @return Cookie or null
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) return null;
        for (Cookie ck : cookies) {
            if (StringUtils.equalsIgnoreCase(name,ck.getName()))
                return ck;
        }
        return null;
    }

    /**
     * 获取COOKIE的值
     * @param request HttpServletRequest
     * @param name Cookie的名称
     * @return CookieValue or null
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) return null;
        for (Cookie ck : cookies) {
            if (StringUtils.equalsIgnoreCase(name,ck.getName()))
                return ck.getValue();
        }
        return null;
    }

    /**
     * 设置COOKIE
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param name  Cookie的名称
     * @param value Cookie的值
     * @param maxAge 有效时长
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
            String value, int maxAge) {
        setCookie(request,response,name,value,maxAge,true);
    }

    /**
     * 设置COOKIE
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param name  Cookie的名称
     * @param value Cookie的值
     * @param maxAge 有效时长
     * @param all_sub_domain 域名
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
            String value, int maxAge, boolean all_sub_domain) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        if(all_sub_domain){
            String serverName = request.getServerName();
            String domain = getDomainOfServerName(serverName);
            if(domain!=null && domain.indexOf('.')!=-1){
                cookie.setDomain('.' + domain);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param name Cookie的名称
     * @param all_sub_domain 域名
     */
    public static void deleteCookie(HttpServletRequest request,
            HttpServletResponse response, String name, boolean all_sub_domain) {
        setCookie(request,response,name,"",0,all_sub_domain);
    }

    /**
     * 获取用户访问URL中的根域名
     * 例如: www.dlog.cn -> dlog.cn
     * @param host 域名
     * @return 根域名
     */
    public static String getDomainOfServerName(String host){
        if(isIPAddr(host))
            return null;
        String[] names = StringUtils.split(host, '.');
        int len = names.length;
        if(len==1) return null;
        if(len==3){
            return makeup(names[len-2],names[len-1]);
        }
        if(len>3){
            String dp = names[len-2];
            if(dp.equalsIgnoreCase("com")||dp.equalsIgnoreCase("gov")||dp.equalsIgnoreCase("net")||dp.equalsIgnoreCase("edu")||dp.equalsIgnoreCase("org"))
                return makeup(names[len-3],names[len-2],names[len-1]);
            else
                return makeup(names[len-2],names[len-1]);
        }
        return host;
    }

    /**
     * 判断字符串是否是一个IP地址
     * @param addr 字符串
     * @return true:IP地址，false：非IP地址
     */
    public static boolean isIPAddr(String addr){
        if(StringUtils.isEmpty(addr))
            return false;
        String[] ips = StringUtils.split(addr, '.');
        if(ips.length != 4)
            return false;
        try{
            int ipa = Integer.parseInt(ips[0]);
            int ipb = Integer.parseInt(ips[1]);
            int ipc = Integer.parseInt(ips[2]);
            int ipd = Integer.parseInt(ips[3]);
            return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0
                    && ipc <= 255 && ipd >= 0 && ipd <= 255;
        }catch(Exception e){}
        return false;
    }

    /**
     * 把字符串数组串起来，中间加“.”，用于域名的串接
     * @param ps 字符串数组
     * @return 字符串
     */
    private static String makeup(String...ps){
        StringBuilder s = new StringBuilder();
        for(int idx = 0; idx < ps.length; idx++){
            if(idx > 0)
                s.append('.');
            s.append(ps[idx]);
        }
        return s.toString();
    }

    /**
     * 获取HTTP端口
     * @param req HttpServletRequest
     * @return 端口数值
     * @throws java.net.MalformedURLException
     */
    public static int getHttpPort(HttpServletRequest req) {
        try {
            return new URL(req.getRequestURL().toString()).getPort();
        } catch (MalformedURLException excp) {
            return 80;
        }
    }

    /**
     * 获取浏览器提交的整形参数
     * @param req HttpServletRequest
     * @param param 参数名
     * @param defaultValue 默认值
     * @return int
     */
    public static int getParam(HttpServletRequest req, String param, int defaultValue){
        return NumberUtils.toInt(req.getParameter(param), defaultValue);
    }
    /**
     * 获取浏览器提交的整形参数
     * @param req HttpServletRequest
     * @param param 参数名
     * @param defaultValue 默认值
     * @return long
     */
    public static long getParam(HttpServletRequest req, String param, long defaultValue){
        return NumberUtils.toLong(req.getParameter(param), defaultValue);
    }

    /**
     * 对getParameterValues的封装，转换成long数组
     * @param req HttpServletRequest
     * @param name  参数名
     * @return long数组
     */
    public static long[] getParamValues(HttpServletRequest req, String name){
        String[] values = req.getParameterValues(name);
        if(values==null) return null;
        return (long[])ConvertUtils.convert(values, long.class);
    }

    /**
     * 获取浏览器提交的字符串参数
     * @param req HttpServletRequest
     * @param param  参数名
     * @param defaultValue 默认值
     * @return String
     */
    public static String getParam(HttpServletRequest req, String param, String defaultValue){
        String value = req.getParameter(param);
        return (StringUtils.isEmpty(value))?defaultValue:value;
    }

    /**
     * 格式化中文字符，防止出现乱码
     * @param str
     * @return
     */
    private static String codeToString(String str) {
        String strString = str;
        try {
            byte tempB[] = strString.getBytes("ISO-8859-1");
            strString = new String(tempB);
            return strString;
        } catch (Exception e) {
            return strString;
        }
    }

    /**
     * 获取完整的Url
     * @param request
     * @return
     * @throws Exception
     */
    public static String getBackUrl(HttpServletRequest request) throws Exception {
        String strBackUrl = "";
        try {
        strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getServletPath() + "?" + codeToString(request.getQueryString());    
        strBackUrl = java.net.URLEncoder.encode(strBackUrl,"gbk");
        } catch(Exception e) {
            throw e;
        }
        return strBackUrl;
    }
    /**
     *
     * @return 获得本机IP内网地址
     */
    public static String getLocalIP()
    {
        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            InetAddress ip = null;
            boolean finded = false;// 是否找到外网IP
            while (netInterfaces.hasMoreElements() && !finded) {
                NetworkInterface ni = netInterfaces.nextElement();
                if(ni.getName().equals("eth0")){
                    Enumeration<InetAddress> address = ni.getInetAddresses();
                    while (address.hasMoreElements()) {
                        ip = address.nextElement();
                        if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                                && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                            netip = ip.getHostAddress();
                            finded = true;
                            break;
                        } else if (ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()
                                && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                            localip = ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }

    /**
     * 获取本机IP地址，并自动区分Windows还是Linux操作系统
     *
     * @return String
     */
    public static String getLocalIpForWinOrLinux() {
        String sIP = "";
        InetAddress ip = null;
        try {
            //如果是Windows操作系统
            if (isWindowsOS()) {
                ip = InetAddress.getLocalHost();
                //如果是Linux操作系统
            } else {
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                        .getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = (InetAddress) ips.nextElement();
                        if (ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()   //127.开头的都是lookback地址
                                && ip.getHostAddress().indexOf(":") == -1) {
                            bFindIP = true;
                            break;
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }

    public static String getLoadlIpByOS(){
        String sIP = "";
        InetAddress ip = null;
        try {
            //如果是Windows操作系统
            if (isWindowsOS()) {
                ip = InetAddress.getLocalHost();
                //如果是Linux操作系统
            } else {
                return getLocalIP();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }

    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    public static SysUser getCurrentUser(){
        return (SysUser) SpringSecurityUtils.getCurrentUser();
    }
}